package com.smartStatus.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.smartStatus.admin.service.*;
import com.smartStatus.admin.utils.JoinUtil;
import com.smartStatus.api.entity.*;
import com.smartStatus.api.vo.SysDepartmentVO;
import com.smartStatus.api.vo.TenantDepartmentVO;
import com.smartStatus.core.constant.SysUser;
import com.smartStatus.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smartStatus.core.util.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统学校表 Controller
 *
 * @author lby
 * @since 2021-03-06
 */
@RestController
@Slf4j
@Api(value = "SysTenantController", tags = "SysTenant管理")
@AllArgsConstructor
@RequestMapping("/SysTenant")
public class SysTenantController {

    private final SysTenantService sysTenantService;
    private final SysDepartmentService sysDepartmentService;
    private final SysMajorService sysMajorService;
    private final DepartmentMajorService departmentMajorService;
    private final TenantDepartmentService tenantDepartmentService;
    private final SysUserTenantService sysUserTenantService;

    /**
     * 分页数据
     */
    @PreAuthorize("@pms.hasPermission('sys_tenant_view')")
    @ApiOperation(value = "公共参数分页数据")
    @GetMapping("/page")
    public R sysTenantPage(Page<SysTenant> page, SysTenant sysTenant) {
        QueryWrapper<SysTenant> query = Wrappers.query();
        SysUser sysUser = SecurityUtils.getUser().getSysUser();
        if (sysUser != null) {
            QueryWrapper<SysUserTenant> query1 = Wrappers.query();
            query1.eq("user_id", sysUser.getUserId());
            SysUserTenant one = sysUserTenantService.getOne(query1);
            if (one != null && one.getTenantId() != 0) {
                query.eq("id", one.getTenantId());
            }
        }
        return R.ok(sysTenantService.page(page, query));
    }


    /**
     * 列表数据
     */
    @PreAuthorize("@pms.hasPermission('sys_tenant_view')")
    @ApiOperation(value = "公共参数列表")
    @GetMapping("/list")
    public R sysTenantList() {
        return R.ok(sysTenantService.list());
    }


    /**
     * 编辑数据
     */
    @PreAuthorize("@pms.hasPermission('sys_tenant_view')")
    @ApiOperation(value = "编辑公共参数")
    @ApiImplicitParam(name = "SysTenant", value = "SysTenant实体", required = true, dataType = "SysTenant")
    @PutMapping("/edit")
    public R sysTenantUpdate(@RequestBody SysTenant sysTenant) {
        return R.ok(sysTenantService.updateById(sysTenant));
    }


    /**
     * 删除数据
     */
    @PreAuthorize("@pms.hasPermission('sys_tenant_view')")
    @ApiOperation(value = "删除公共参数")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "Integer")
    @DeleteMapping("/{id}")
    public R sysTenantDelete(@PathVariable Integer id) {
        return R.ok(sysTenantService.removeById(id));
    }

    /**
     * 添加数据
     */
    @PreAuthorize("@pms.hasPermission('sys_tenant_view')")
    @ApiOperation(value = "添加公共参数")
    @ApiImplicitParam(name = "SysTenant", value = "SysTenant实体", required = true, dataType = "SysTenant")
    @PostMapping("/add")
    public R sysTenantInsert(@RequestBody SysTenant sysTenant) {
        return R.ok(sysTenantService.save(sysTenant));
    }


    /**
     * 用户给学校绑定院校
     *
     * @param tenantDepartmentList
     * @return
     */
    @PreAuthorize("@pms.hasPermission('sys_tenant_view')")
    @ApiOperation(value = "用户给学校绑定院校")
    @PostMapping("/bind-department")
    public R bindDepartment(@RequestBody List<TenantDepartment> tenantDepartmentList) {
        QueryWrapper<TenantDepartment> query = Wrappers.query();
        query.eq("tenant_id", tenantDepartmentList.get(0).getTenantId());
        tenantDepartmentService.remove(query);
        return R.ok(tenantDepartmentService.saveBatch(tenantDepartmentList), "绑定成功");
    }


    /**
     * 获取学校可以选择绑定的数据
     *
     * @param
     * @return
     */
    @PreAuthorize("@pms.hasPermission('sys_tenant_view')")
    @ApiOperation(value = "用户给学校绑定院校")
    @GetMapping("/bind-data")
    public R getDepartment() {
        // 查询已经绑定成功的数据
        Integer tenantId = SecurityUtils.getUser().getTenantId();
        SysTenant one = sysTenantService.getById(tenantId);
        QueryWrapper<TenantDepartment> query = Wrappers.query();
        query.eq("tenant_id", tenantId);
        List<TenantDepartment> list2 = tenantDepartmentService.list(query);
        List<TenantDepartmentVO> list3 = JoinUtil.list(list2, TenantDepartmentVO.class);
        list3.forEach(tenantDepartmentVO -> {
            tenantDepartmentVO.setTenantName(one.getName());
            SysDepartment byId = sysDepartmentService.getById(tenantDepartmentVO.getDepartmentId());
            SysMajor byId1 = sysMajorService.getById(tenantDepartmentVO.getMajorId());
            tenantDepartmentVO.setDepartmentName(byId.getName());
            tenantDepartmentVO.setMajorName(byId1.getName());
        });
        // 差全部
        List<SysDepartment> list = sysDepartmentService.list();
        List<SysDepartmentVO> list1 = JoinUtil.list(list, SysDepartmentVO.class);
        list1.forEach(sysDepartmentVO -> {
            List<SysMajor> majors = sysMajorService.getMajors(sysDepartmentVO);
            sysDepartmentVO.setMajorList(majors);
        });
        // 计算出未绑定数据
        for (int i = 0; i < list1.size(); i++) {
            for (int j = 0; j < list3.size(); j++) {
                if (list3.get(j).getDepartmentId().equals(list1.get(i).getId())) {
                    list1.remove(i);
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("totalData", list1);
        map.put("checkedData", list3);
        return R.ok(map);

    }
}
